package com.wwz.frame.exception;

import com.alibaba.fastjson.JSONObject;
import com.wwz.frame.entity.ResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;
/**  
* @Description
* @Author wwz
* @Date 2019/09/24 
* @Param   
* @Return   
*/ 
@RestControllerAdvice
@Component
public class GlobalValidExceptionHandler {
    /**
     * 处理请求对象属性不满足校验规则的异常信息
     * 捕获MethodArgumentNotValidException，获取BindingResult返回值，直接获取BindingException会失败， 该处理方式可以节省在controller方法上写BindingResult返回属性
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String exception(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder msg = new StringBuilder();
        for (FieldError error : fieldErrors) {
            msg.append(error.getField() + ":" + error.getDefaultMessage() + ";");
        }
        ResponseVo result = new ResponseVo();
        result.setCode(400);
        result.setMessage(msg.toString());

        return JSONObject.toJSONString(result);
    }

    /**
     * 处理请求单个参数不满足校验规则的异常信息
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public String constraintViolationExceptionHandler(ConstraintViolationException exception) {
        return exception.getMessage();
    }
}
